package mysql

import (
	"go.uber.org/zap"
	"struggle/model"
)

func CreateAnswer(answer *model.Answer) (err error) {
	sqlStr := `INSERT INTO st_answer (answer_id, content, author_id, question_id) VALUES (?, ?, ?, ?)`
	_, err = db.Exec(sqlStr, answer.AnswerID, answer.Content, answer.AuthorID, answer.QuestionID)
	if err != nil {
		zap.L().Error("create answer failed", zap.Error(err))
		return
	}
	return
}

func GetAnswerList(questionID uint64, offset, limit int) (answerList []*model.Answer, err error) {
	sqlStr := `SELECT answer_id, content, vote_up_count, author_id, status, create_time, update_time from st_answer where question_id = ? order by id desc limit ?, ?`
	err = db.Select(&answerList, sqlStr, questionID, offset, limit)
	if err != nil {
		zap.L().Error("GetAnswerList failed", zap.Error(err))
		return
	}
	return
}

// 获取该问题有多少回答
func GetAnswerCount(questionID uint64) (answerCount int, err error) {
	sqlStr := `SELECT count(answer_id) from st_answer where question_id = ?`
	err = db.Get(&answerCount, sqlStr, questionID)
	if err != nil {
		zap.L().Error("GetAnswerCount failed", zap.Error(err))
		return
	}
	return
}

// 获取该问题的最近一个回答的作者和时间
func GetAnswerLately(questionID uint64) (answer *model.Answer, err error) {
	answer = &model.Answer{}
	sqlStr := `SELECT author_id, status, create_time, update_time from st_answer where question_id = ? order by id desc limit 1`
	err = db.Get(answer, sqlStr, questionID)
	if err != nil {
		zap.L().Error("GetAnswerList failed", zap.Error(err))
		return
	}
	return
}

// 获取该用户已回答多少问题
func GetUserAnswerCount(sn uint64) (answerCount int, err error) {
	sqlStr := `SELECT count(question_id) FROM st_answer WHERE author_id = ?`
	err = db.Get(&answerCount, sqlStr, sn)
	if err != nil {
		zap.L().Error("GetUserAnswerCount failed", zap.Error(err))
		return
	}
	return
}

type answerDAO struct{}

var DefaultAnswer = answerDAO{}

// UpdateExZan 更新问题扩展表字段 称赞的数量
func (a answerDAO) UpdateExZan(sn uint64, count int) error {
	sqlStr := `UPDATE st_answer SET vote_up_count = ? WHERE answer_id = ?`
	_, err := db.Exec(sqlStr, count, sn)
	if err != nil {
		zap.L().Error("update answer zan num failed", zap.Error(err))
		return err
	}
	return err
}

// 根据回答编号返回作者编号
func (a answerDAO) GetAuthor(sn uint64) (author uint64, err error) {
	sqlStr := `SELECT author_id FROM st_answer WHERE answer_id = ? LIMIT 1`
	err = db.Get(&author, sqlStr, sn)
	if err != nil {
		zap.L().Error("according answer sn find user sn failed", zap.Error(err))
		return
	}
	return
}

// GetAuthorZan 返回该用户所有回答赞的总数
func (a answerDAO) GetAuthorZan(sn uint64) (count int, err error) {
	sqlStr := `SELECT sum(vote_up_count) FROM st_answer WHERE author_id=?`
	err = db.Get(&count, sqlStr, sn)
	if err != nil {
		zap.L().Error("according user sn find zan count failed", zap.Error(err))
		return
	}
	return
}
